package com.pansoft.openplanet.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.EasyPermissionUtils;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.activity.child.ChildRestoreWalletActivityTwo;
import com.pansoft.openplanet.activity.child.CreateChildWalletActivity;
import com.pansoft.openplanet.activity.child.CreateEosWalletActivity;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.util.EosNetParamUtil;
import com.pansoft.openplanet.widget.SelectAvatarDialog;
import com.utilcode.util.ToastUtils;

import java.io.File;

import pub.devrel.easypermissions.AfterPermissionGranted;

import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_CUT;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_GALLERY;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * @author will
 * 钱包头像和名称设置
 */
public class WalletAvatarAndNameSetupActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "WalletAvatarAndNameSetu";

    private ImageView ivIcon;
    private EditText etName;
    private Button tvSetAvatar;
    private String pictureUrlPath;//头像在网络上的位置
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪
    private SelectAvatarDialog selectAvatarDialog;
    private int mode = WalletTypeSelectActivity.MODE_CREATE_NEW;
    /** 是否是创建卡片冷钱包 **/
    private boolean isCardColdWallet;

    /**
     * @param context
     * @param mode    创建或者恢复钱包
     */
    public static void start(Context context, int mode, int chainId) {
        Intent starter = new Intent(context, WalletAvatarAndNameSetupActivity.class);
        starter.putExtra("mode", mode);
        starter.putExtra("chainId", chainId);
        context.startActivity(starter);
    }

    /**
     * @param context
     * @param mode    创建卡片冷钱包
     */
    public static void start(Context context, int mode, int chainId, boolean isCardColdWallet) {
        Intent starter = new Intent(context, WalletAvatarAndNameSetupActivity.class);
        starter.putExtra("mode", mode);
        starter.putExtra("chainId", chainId);
        starter.putExtra("isCardColdWallet", isCardColdWallet);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.open_planet_activity_setup_wallet_avatar_name);
        isCardColdWallet = getIntent().getBooleanExtra("isCardColdWallet", false);
        pictureAndCropManager = new PictureAndCropManager(this);
        selectAvatarDialog = new SelectAvatarDialog(this, pictureAndCropManager);
        if (getIntent() != null && getIntent().getExtras() != null) {
            mode = getIntent().getIntExtra("mode", WalletTypeSelectActivity.MODE_CREATE_NEW);
        }
        initView();
    }

    private void initView() {
        TextView tvName = (TextView) findViewById(R.id.tv_title);
        tvName.setText(ResStringUtil.getString(R.string.open_planet_asset_wallet_avatar_name_setup));
        ivIcon = (ImageView) findViewById(R.id.iv_icon);
        etName = (EditText) findViewById(R.id.et_name);
        tvSetAvatar = (Button) findViewById(R.id.tv_set_avatar);
        ivIcon.setOnClickListener(this);
        tvSetAvatar.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_icon) {
            selectAvatarDialog.show();
        } else if (id == R.id.tv_set_avatar) {
            if (etName.getText().toString().equals("")) {
                ToastUtils.showShort(ResStringUtil.getString(R.string.open_planet_asset_wallet_enter_name));
                return;
            }

            pictureUrlPath = pictureUrlPath == null ? "" : pictureUrlPath;
            int chainId = getIntent().getIntExtra("chainId", IPAssetsConstant.CHAIN_ID_ETH);

            if (mode == WalletTypeSelectActivity.MODE_CREATE_NEW) {
                //新建
                if (chainId == EosNetParamUtil.getEosChainId()) {
                    Intent intent = new Intent(this, CreateEosWalletActivity.class);
                    intent.putExtra("number", EnvironmentVariable.getUserName());
                    intent.putExtra("wallet_avatar", pictureUrlPath);
                    intent.putExtra("wallet_name", etName.getText().toString());
                    startActivity(intent);
                    finish();
                } else {
                    Intent intent = new Intent(this, CreateChildWalletActivity.class);
                    intent.putExtra("isCardColdWallet", isCardColdWallet);
                    intent.putExtra("chainId", chainId);
                    intent.putExtra("wallet_avatar", pictureUrlPath);
                    intent.putExtra("wallet_name", etName.getText().toString());
                    startActivity(intent);
                }
            } else if (mode == WalletTypeSelectActivity.MODE_RESTORE_OLD) {
                //导入
                Intent intent = new Intent(this, ChildRestoreWalletActivityTwo.class);
                intent.putExtra("chainId", getIntent().getIntExtra("chainId",
                        IPAssetsConstant.CHAIN_ID_ETH));
                intent.putExtra("number", EnvironmentVariable.getUserName());
                intent.putExtra("wallet_avatar", pictureUrlPath);
                intent.putExtra("wallet_name", etName.getText().toString());
                startActivity(intent);
                //测试BreadWallet
//                BTCWalletManager btcWalletManager = new BTCWalletManager(this);
//                btcWalletManager.restoreWalletbyMnemonic("awkward decorate lunar fancy foster write taxi column family derive tattoo absent",
//                        "", "11", new BTCWalletManager.BTCWalletRestoreListener() {
//                            @Override
//                            public void onRestoreSuccess(Account account) {
//
//                            }
//
//                            @Override
//                            public void onRestoreFail() {
//
//                            }
//                        });
            }
        }
    }

    @AfterPermissionGranted(EasyPermissionUtils.PERMISSION_REQUEST_CODE_CAMERA)
    private void startTakePhoto() {
        //这个方法不多余，勿删
        if (EasyPermissionUtils.checkCameraPermission() && selectAvatarDialog != null) {
            selectAvatarDialog.startTakePhoto();
        }
    }

    @SuppressLint("SdCardPath")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    if (pictureAndCropManager.getPicturePath() == null) {
                        ToastUtil.showToast(AppContext.getInstance(), R.string.open_planet_get_pic_path_fail);
                        return;
                    }
                    pictureAndCropManager.startPhotoZoom(Uri.fromFile(
                            new File(pictureAndCropManager.getPicturePath())), 300);
                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null) {
                        pictureAndCropManager.startPhotoZoom(data.getData(), 300);
                    }
                    break;

                case PHOTO_REQUEST_CUT:
//                    Log.i("剪裁后头像文件路径：", pictureAndCropManager.getPicturePath());
                    if (!isNetActive()) {
                        ToastUtils.showShort(R.string.common_text_network_error_please_again);
                        return;
                    }
                    showLoading(ResStringUtil.getString(R.string.common_text_uploading_avatar));

                    try {
                        PansoftCloudUtil.getCloudRes(pictureAndCropManager.getPicturePath(), new PansoftCloudUtil.UpLoadListener() {
                            @Override
                            public void getHttpUrl(Boolean isSuccess, String url) {
                                dismissLoading();
                                if (isSuccess) {
//                                    Log.i(TAG, "---头像在云盘服务器上的路径:" + url);
                                    pictureUrlPath = url;
                                    pictureUrlPath.trim();
                                    ToastUtils.showShort(R.string.common_text_upload_success);
                                    LXGlideImageLoader.getInstance().showRoundUserAvatar(WalletAvatarAndNameSetupActivity.this,
                                            ivIcon, pictureUrlPath, 20);
                                } else {
                                    ToastUtils.showShort(R.string.common_text_upload_fail_again);
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    break;
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
